package com.hmsm.sys.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.hmsm.server.base.BaseAction;
import com.hmsm.server.common.CommonUtil;
import com.hmsm.server.util.MD5;
import com.hmsm.server.util.ProperConfig;
import com.hmsm.server.util.Util;
import com.hmsm.sys.bean.DeptTypeEnum;
import com.hmsm.sys.bean.RTXDeptBean;
import com.hmsm.sys.controller.LoginController;
import com.hmsm.sys.controller.RtxLoginController;
import com.hmsm.sys.dto.RTXDeptDto;
import com.hmsm.sys.dto.RTXUserDto;
import com.hmsm.sys.po.DeptInfo;
import com.hmsm.sys.po.OrgInfo;
import com.hmsm.sys.po.UserInfo;
import com.hmsm.sys.po.UserOrg;
import com.hmsm.sys.service.DeptInfoService;
import com.hmsm.sys.service.DynamicCipherCardService;
import com.hmsm.sys.service.UserOrgService;

public class RtxManagerAction extends BaseAction<UserInfo>{
	
	private static final long serialVersionUID = 2082368413225426201L;

	@Resource(name="loginController")
	public void setLoginController(LoginController loginController){
		setBaseController(loginController);
	}
	
	public LoginController getLoginController() {
		return (LoginController) getBaseController();
	}
	
	@Resource(name="rtxLoginController")
	private RtxLoginController rtxLoginController;
	
	@Resource
	private DeptInfoService deptInfoService;
	
	public DeptInfoService getDeptInfoService() {
		return deptInfoService;
	}
	public void setDeptInfoService(DeptInfoService deptInfoService) {
		this.deptInfoService = deptInfoService;
	}
	
	@Resource
	private UserOrgService userOrgService;

	public UserOrgService getUserOrgService() {
		return userOrgService;
	}
	public void setUserOrgService(UserOrgService userOrgService) {
		this.userOrgService = userOrgService;
	}

	@Resource
	private DynamicCipherCardService dynamicCipherCardService;
	
	public DynamicCipherCardService getDynamicCipherCardService() {
		return dynamicCipherCardService;
	}

	public void setDynamicCipherCardService(DynamicCipherCardService dynamicCipherCardService) {
		this.dynamicCipherCardService = dynamicCipherCardService;
	}
	
	@Resource
	private OrgTreeHelper orgTreeHelper;
	
	private String userName;
	private String password;
	private String json;
	private List<UserInfo> userLists;
	private List<String[]> deptList;
	private int deptId;
	private String userMessage;
	private String deptMessage;
	private UserInfo user;
	private String message;
	private String id;
	private String par;
	private String parAction;
	private int userId;
	private String code;
	private String syncData;
	private String rtxuser;
	private String sign;

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getParAction() {
		return parAction;
	}

	public void setParAction(String parAction) {
		this.parAction = parAction;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getPar() {
		return par;
	}

	public void setPar(String par) {
		this.par = par;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

	public String getUserMessage() {
		return userMessage;
	}

	public void setUserMessage(String userMessage) {
		this.userMessage = userMessage;
	}

	public String getDeptMessage() {
		return deptMessage;
	}

	public void setDeptMessage(String deptMessage) {
		this.deptMessage = deptMessage;
	}

	public int getDeptId() {
		return deptId;
	}

	public void setDeptId(int deptId) {
		this.deptId = deptId;
	}

	public List<UserInfo> getUserLis() {
		return userLists;
	}

	public List<UserInfo> getUserLists() {
		return userLists;
	}

	public void setUserLists(List<UserInfo> userLists) {
		this.userLists = userLists;
	}

	public List<String[]> getDeptList() {
		return deptList;
	}

	public void setDeptList(List<String[]> deptList) {
		this.deptList = deptList;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
	public String getSyncData() {
		return syncData;
	}

	public void setSyncData(String syncData) {
		this.syncData = syncData;
	}

	public String getRtxuser() {
		return rtxuser;
	}

	public void setRtxuser(String rtxuser) {
		this.rtxuser = rtxuser;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public RtxManagerAction(){
		
	}
	
	/**
	 * 统一登录
	 * @return
	 * @author 舒俊
	 * 2013-10-22 下午01:50:47
	 * return:
	 */
	public String rhsLogin(){
		UserInfo currentUser = getSessionUser();
		if(currentUser==null){
			setMessage("RTX登录失败，请重新从腾讯通客户端登录后进入！");
			this.logError(this,getMessage());
			addActionError(getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	public String rtxLogin(){
		String viewName;
		
		ModelAndView modelAndView = rtxLoginController.login(rtxuser, sign, getRequest());
		viewName = modelAndView.getViewName();
		
		return viewName;
	}
	
	public String validateRtxUser(){
		boolean result = false;
		
		String accountSource = "RTX_001";
	
		UserInfo userInfo = null;
		try {
			userInfo = getUserInfoService().login(accountSource, userName, password);
		} catch (Exception e) {
			e.printStackTrace();
			mapResult.put("errorMessage", "腾讯通登陆发生错误："+e.getMessage());
		}
	
		if (userInfo==null) {
			result = false;
			mapResult.put("errorMessage", "腾讯通用户未登陆!");
		} else {
			// 基本可以确定登录成功
			Map<String, Object> user = new HashMap<String, Object>();
			user.put("userName",userInfo.getUserName());
			mapResult.put("user", user);
			result = true;
		}
		
		mapResult.put("success", result);
		return "json";
	}
	
	/**
	 * 腾讯通模拟登录
	 * @return
	 * @author 舒俊
	 */
	public String reRxtLogin(){
		if(id==null){
			return ERROR;
		}
		if(message==null){
			return ERROR;
		}
		String viewName = SUCCESS;
		
		ModelAndView modelAndView = getLoginController().reRtxLogin(userId, message, parAction, getRequest());
		viewName = modelAndView.getViewName();
		
		return viewName;
	}

	/**
	 *  @描述:腾讯通登陆时记录标识
	 *  @方法名称:getRtxMarkInfo
	 *  @作者:fengtao
	 *  @创建日期:2014-4-22 下午01:42:39 
	 *  @return
	 **/
	public void getRtxMarkInfo(){
		String value = null;
		
		value = getLoginController().getSyncMarkInfo(syncData);
		
		if(StringUtils.isBlank(value)){
			this.writeResponse("");
		}else{
			this.writeResponse(value);
		}
	}
	
	/**
	 *  @描述:同步数据
	 *  @方法名称:syncData
	 *  @作者:fengtao
	 *  @创建日期:2014-4-22 下午02:31:50 
	 **/
	public void syncData(){
		String str = null;
		
		UserInfo currentUser = getSessionUser();
		str = getLoginController().getSyncDataKey(userName, currentUser);
		
		if(str==null){
			this.writeResponse("-1");
		}else{
			this.writeResponse(str);
		}
	}
	
	/**
	 * 打开腾讯通管理页面
	 * @return
	 * @author 何杰 2013-2-21
	 */
	public String openRtxManagerPage(){
		List<RTXDeptDto> deptBean = new ArrayList<RTXDeptDto>();// 部门集合
		List<RTXUserDto> userBean = new ArrayList<RTXUserDto>();// 用户集合
		List<DeptInfo> deptInfos = getDeptInfoService().getAllDept();//获取所有的部门
		List<UserInfo> userListAll = getUserInfoService().getAll();//获取添加的所有用户

		//移除管理员
		List<String> userNameAll = new ArrayList<String>();
		List<String> tempAll = new ArrayList<String>();
		userLists = new ArrayList<UserInfo>();
		for(int i=0;i<userListAll.size();i++){
			UserInfo user = userListAll.get(i);
			if(user.getType().equals(2)){
				continue;
			}
			user.setState(0);
			for(int j=0;j<userBean.size();j++){
				RTXUserDto rud =  userBean.get(j);
				if(rud.getUserName().equals(user.getUserName())){
					user.setState(1);
					break;
				}
			}
			userLists.add(user);
			if(userNameAll.contains(user.getUserName())){
				tempAll.add(user.getUserName());
			}else{
				userNameAll.add(user.getUserName());
			}
		}
		deptList = new ArrayList<String[]>();
		for (DeptInfo deptInfo : deptInfos) {
			String[] dept = new String[6];
			if (deptInfo.getParId() == 0) {
				//机构
				dept[0] = deptInfo.getPkId().toString();
				dept[1] = deptInfo.getName();
				dept[2] = deptInfo.getType().toString();//是否营业厅
				dept[3] = deptInfo.getName();
				dept[4] = deptInfo.getDeptNo();
			}else{
				//部门
				dept[0] = deptInfo.getPkId().toString();
				dept[1] = deptInfo.getName();
				dept[2] = deptInfo.getType().toString();//是否营业厅
				String sbOrg = deptInfo.getName();
				dept[4] = deptInfo.getDeptNo();
				while (deptInfo.getParId().intValue()!=0) {
					deptInfo = getDeptInfoService().getById(deptInfo.getParId());
					if(deptInfo!=null){
						sbOrg = deptInfo.getName()+">"+sbOrg;// 获取机构名称
					}else{
						break;
					}
				}
				dept[3] = sbOrg;
			}
			dept[5] = "0"; 
			for(int i=0;i<deptBean.size();i++){
				if(deptBean.get(i).getDeptId()==deptInfo.getIdType()){
					dept[5] = "1";
				}
			}
			deptList.add(dept);
		}
		String str = "";
		for(int i=0;i<tempAll.size();i++){
			if(i>0){
				str += ",";
			}
			str += tempAll.get(i);
		}
		this.setMessage(str);
		try {
			json = getSyncManageTree();

		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}

	private String getSyncManageTree() throws Exception {
		UserInfo currentUser = getSessionUser();

		// 获取组织机构绑定关系树，包含用户
		RTXDeptBean rtxDeptTreeNode = orgTreeHelper.getRootDept(orgTreeHelper.getOrgManageRight(), true, currentUser);
		orgTreeHelper.loadSubDepts(rtxDeptTreeNode, true, true, -1);

		return orgTreeHelper.getOrgTree(rtxDeptTreeNode);
	}
	
	/**
	 * 删除机构 2013-11-23 20:19:49修改为递归方式删除部门及用户信息
	 * @return
	 * @author 何杰 2013-2-21
	 */
	public String deleteDept(){
		DeptInfo dept = (DeptInfo) getDeptInfoService().getById(deptId);//获取部门信息
		try {
			getDeptInfoService().deleteDeptAndUserAll(dept);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("发生错误："+e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 添加腾讯通用户
	 * @return
	 * @author 何杰 2013-2-21
	 */
	public String addRtxUser(){
		Util util = new Util();
		boolean isboolean = true;
		String[] users = util.getSplitComplex(userMessage, "|");//获取选择的用户数组
		String[] depts = util.getSplitComplex(deptMessage, "|");//获取选择的部门数组
		
		try {
			List<DeptInfo> deptList = getDeptInfoService().getAllDept();//获取所有部门
			List<UserInfo> userList = getUserInfoService().getAll();//获取所有用户
			for (int i = 1; i < depts.length; i++) {
				DeptInfo tempDept = null;
				isboolean = true;
				String[] dept = util.getSplitComplex(depts[i], ",");
				for (DeptInfo list : deptList) {
					//判断部门是否重复
					if(list.getIdType() == Integer.parseInt(dept[0])){
						tempDept = list;
						isboolean  = false;
						break;
					}
				}
				if(isboolean){
					if (Integer.parseInt(dept[1]) == 0) {
						//机构
						OrgInfo orgInfo = new OrgInfo();
						orgInfo.setName(dept[2]);//设置机构名称
						orgInfo.setState(1);//设置机构状态
						orgInfo.setIdType(Integer.parseInt(dept[0]));
						orgInfo = getDeptInfoService().saveOrgInfo(orgInfo);//保存机构信息
						DeptInfo deptInfo = new DeptInfo();
						deptInfo.setName(dept[2]);//设置部门名称
						deptInfo.setDeptType(DeptTypeEnum.GENERAL.getValue());
						deptInfo.setOrgId(orgInfo.getPkId());//设置机构ID
						deptInfo.setParId(0);//设置父级机构ID
						deptInfo.setState(1);//设置状态
						deptInfo.setIdType(Integer.parseInt(dept[0]));
						deptInfo.setType(0);//是否营业厅：1是0否
						deptInfo = (DeptInfo) getDeptInfoService().save(deptInfo);//保存部门信息
					}else{
						//部门
						DeptInfo deptInfo = new DeptInfo();
						DeptInfo deptinfo2 = getDeptInfoService().getDeptByRtxId(Integer.parseInt(dept[1]));
						deptInfo.setName(dept[2]);//设置部门名称
						deptInfo.setDeptType(DeptTypeEnum.GENERAL.getValue());
						deptInfo.setOrgId(getDeptInfoService().getById(deptinfo2.getPkId()).getOrgId());//设置机构ID
						deptInfo.setParId(deptinfo2.getPkId());//设置父级机构ID
						deptInfo.setState(1);//设置状态
						deptInfo.setIdType(Integer.parseInt(dept[0]));
						deptInfo.setType(0);//是否营业厅：1是0否
						deptInfo = (DeptInfo) getDeptInfoService().save(deptInfo);//保存部门信息
					}
				}else{
					if(tempDept!=null){
						try {
							if (Integer.parseInt(dept[1]) == 0) {
								//机构
								OrgInfo orgInfo = new OrgInfo();
								orgInfo.setIdType(Integer.parseInt(dept[0]));
								orgInfo.setState(1);//设置机构状态
								List<OrgInfo> orgInfoAll =  getDeptInfoService().getOrgInfoDao().query(orgInfo);
								if(orgInfoAll.size()>0){
									orgInfo = orgInfoAll.get(0);
									orgInfo.setName(dept[2]);//设置机构名称
									getDeptInfoService().getOrgInfoDao().update(orgInfo);
								}else{
									this.logError(this,"新增部门时，机构查询异常["+dept[2]+"]");
								}
								tempDept.setName(dept[2]);
								tempDept.setParId(0);
								getDeptInfoService().update(tempDept);
							}else{
								//部门
								DeptInfo deptinfo2 = getDeptInfoService().getDeptByRtxId(Integer.parseInt(dept[1]));
								tempDept.setName(dept[2]);
								tempDept.setParId(deptinfo2.getPkId());
								getDeptInfoService().update(tempDept);
							}
						} catch (Exception e) {
							e.printStackTrace();
							message = "发生错误："+e;
							addActionError(message);
							return ERROR;
						}
					}
				}
			}
			for (int j = 0; j < users.length; j++) {
				isboolean = true;
				UserInfo tempUser = null;
				String[] user = util.getSplitComplex(users[j], ",");//获取一个用户信息
				// 判断用户是否存在
				for (UserInfo list2 : userList) {
					if (StringUtils.equals(list2.getIdType() + "", user[1])) {
						if(!list2.getUserName().equals(user[3])){//修改了账号（记录日志）
							this.log(this, "腾讯通同步，原账号["+list2.getUserName()+"]修改为["+user[3]+"]");
						}
						tempUser = list2;
						isboolean = false;// 用户存在
						break;
					}
				}
				DeptInfo deptInfo = getDeptInfoService().getDeptByRtxId(Integer.parseInt(user[0]));//获取部门信息
				if(deptInfo==null){
					//无法查询到该部门
					this.logError(this,"无法查询到该部门信息："+user[0]);
					continue;
				}
				int deptId = deptInfo.getPkId();//部门ID
				int orgId = deptInfo.getOrgId();//机构ID
				getDeptInfoService().loadParent(deptInfo);
				String dept = deptInfo.getDeptPathName(0);
				if (isboolean) {
					//添加用户
					UserInfo info = new UserInfo();
					info.setAddress("暂无");
					info.setEmail("暂无");
					info.resetPassword();
					info.setIdType(user[1]);
					info.setName(user[3]);
					info.setState(1);
					info.setTelPhone("暂无");
					info.setUserName(user[2]);
					info.setDepart(deptInfo);
					info.setUserDept(dept);
					info.setType(0);//不是系统管理员
					info.setCreateDate(util.dateToTimestamp(null));
					info.setSnCode(0);
					info = getUserInfoService().save(info, "userName,name,userDepts,passWord,telPhone,email,address,roles", getSessionUser());
					//添加用户部门信息
					UserOrg org = new UserOrg();
					org.setDeptId(deptId);
					org.setOrgId(orgId);
					org.setUserId(info.getPkId());
					org.setState(1);
					getUserOrgService().save(org);
				}else{
					//更新
					if(tempUser!=null){
						tempUser.setName(user[3]);
						tempUser.setUserName(user[2]);
						tempUser.setIdType(user[1]);
						tempUser.setDepart(deptInfo);
//					tempUser.setUserDept(dept);
						try {
							getUserInfoService().save(tempUser, "userName,name,userDepts,passWord,telPhone,email,address,roles", getSessionUser());
						} catch (Exception e) {
							e.printStackTrace();
							message = "发生错误："+e;
							addActionError(message);
							return ERROR;
						}
						//更新用户、部门信息
						UserOrg org = new UserOrg();
						org.setOrgId(orgId);
						org.setUserId(tempUser.getPkId());
						org.setState(1);
						List<UserOrg> orgAll = getUserOrgService().getUserOrgDao().query(org);
						if(orgAll.size()>0){
							org = orgAll.get(0);
							if(org.getDeptId().intValue()!=deptId){
								this.log(this,"更新用户["+tempUser.getUserName()+"]的部门编号["+deptInfo.getName()+"]");
								org.setDeptId(deptId);
								try {
									getUserOrgService().update(org);
								} catch (Exception e) {
									e.printStackTrace();
									message = "发生错误："+e;
									this.logError(this,"用户["+tempUser.getName()+"]更新用户"+message);
									return ERROR;
								}
							}
						}else{
							org.setDeptId(deptId);
							getUserOrgService().save(org);
							this.log(this,"新增用户["+tempUser.getUserName()+"]的部门编号["+deptInfo.getName()+"]");
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message="发生错误："+e;
			addActionError(message);
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 删除用户
	 * @return
	 * @author 何杰 2013-2-22
	 */
	public String deleteRtxUser() {
		try {
			getUserInfoService().deleteById(userId);
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			setMessage("发生错误："+e);
			addActionError(getMessage());
			return ERROR;
		}
	}
	
	/**
	 * 打开新的浏览器，重新启动session
	 * @return
	 */
	public String channelDoc(){
		if(CommonUtil.runType==2){
			//非腾讯通
			this.setMessage("操作非法!");
			return ERROR;
		}
		UserInfo rtxUser = this.getSessionUser();
		if(rtxUser==null){
			// 检查腾讯通登录参数，有的用的是userId，有的用的是 id
			if(userId==0 && !StringUtils.isEmpty(id)){
				userId = Integer.parseInt(id);
			}
			rtxUser = this.getUserInfoService().getById(userId);
			if(rtxUser!=null){
				//再次模拟登录
				this.setSessionUser(rtxUser);
			}
		}
		if(rtxUser == null){
			this.setMessage("用户信息已失效，请重新登录!");
			return ERROR;
		}
		//将验证码设置为用户使用
		id = rtxUser.getPkId()+"";
		message = MD5.getMD5(System.currentTimeMillis()+""+id);
		CommonUtil.userCodeMap.put(rtxUser.getPkId(), message);
		
		if(par!=null){
			//,表示等号，|表示&
			par = par.replaceAll(",", "=");
			par = par.replaceAll("\\u007C", "&");
		}
		if(parAction!=null){
			if(par!=null){
				parAction = parAction+"?"+par;
			}
		}
		return SUCCESS;
	}

}
